/**
 * Created by lenovo on 17-6-6.
 */

var express = require('express');
var router = express.Router();
var http = require('http');
var http_post = require('http-post');
var path = require('path');
var multer  = require('multer');
var storge = multer.diskStorage({
    destination: function (req, file, cb) {
        cb(null, './public/img')
    },
    filename: function (req, file, cb) {
        var fileformat = (file.originalname).split('.');
        cb(null, file.fieldname+'-'+Date.now()+'.'+fileformat[fileformat.length-1]);
    }
});
var upload = multer({ storage: storge});
var checkNotLogin = require('../middlewares/check').checkNotLogin;

router.get('/',checkNotLogin,function(req,res,next){
    res.render('register', { title: 'myblog' });
});

router.post('/', checkNotLogin,function(req,res,next){
    var img_path = (req.body.fileVal).slice(6);
    console.log(img_path)
    var user_info = {
        user: req.body.user,
        password: req.body.password,
        email: req.body.email,
        img: img_path
    };
    http_post("http://localhost:3000/register", user_info,function(response){
        var rawData = '';
        response.setEncoding('utf8');
        response.on('data',function(chunk){
            rawData += chunk;
        }).on("end",function(){
            if(JSON.parse(rawData).status == 200){
                res.json({status:200,message:'注册成功'})
            }else{
                return res.json({status:500,message:'注册失败'})
            }
        })
    }).on("error",function(e){
        console.error(e)
    });
});

/*router.post('/upload', upload.array('file'),function(req,res,next){
    res.json({data:req.files});
});*/ // 多图片上传
router.post('/upload', upload.single('file'),function(req,res,next){
    res.json({data:req.file});
});

router.get('/user',function(req,res,next){
    http.get('http://localhost:3000/user_info?user='+req.query.user,function(response){
        var rawData = '';
        response.setEncoding("utf-8");
        response.on("data", function(chunk){
            rawData += chunk;
        }).on('end',function(){
            return res.json(JSON.parse(rawData))
        })
    })
});

module.exports = router;
